package Service;

import Dao.Impl.UserDAOImpl;
import Dao.Impl.VerificationCodeDAOImpl;
import Dao.UserDAO;
import Dao.VerificationCodeDAO;
import Dto.UserDto;
import entity.User;
import entity.VerificationCode;
import exception.AuthException;
import utils.VerificationCodeUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Su
 * @Date 2025/4/30 10:31
 * @Version 1.0 （版本号）
 */
// UserService.java
public class UserService {
    private UserDAO userDAO;
    private VerificationCodeDAO verificationCodeDAO;
    private EmailService emailService;
    private static final int CODE_EXPIRE_MINUTES = 1;
    private static final int CODE_LENGTH = 6;

    public UserService(Connection connection) {
        this.userDAO = new UserDAOImpl(connection);
        this.verificationCodeDAO = new VerificationCodeDAOImpl(connection);
        this.emailService = new EmailService(connection);
    }

    //注册
    public Map<String, Object> registerUser(String username, String password, String email, String emailCode,String type) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证邮箱验证码
            VerificationCode code = verificationCodeDAO.getValidCode(email, emailCode, type);
            if (code == null) {
                result.put("success", false);
                result.put("message", "验证码无效或已过期");
                return result;
            }

            // 2. 检查用户名和邮箱是否已存在
            if (userDAO.getUserByUsername(username) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }

            if (userDAO.getUserByEmail(email) != null) {
                result.put("success", false);
                result.put("message", "邮箱已被注册");
                return result;
            }

            // 3. 密码加密,暂不考虑
//            String encryptedPassword = BCrypt.hashpw(password, BCrypt.gensalt());

            // 4. 创建用户
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setStatus(1); // 直接激活

            boolean success = userDAO.insertUser(user);
            if (success) {
                result.put("success", true);
                result.put("message", "注册成功");
                result.put("user", user);

                // 删除已使用的验证码
                verificationCodeDAO.deleteExpiredCodes();
            } else {
                result.put("success", false);
                result.put("message", "注册失败，请重试");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误，请稍后再试");
        }

        return result;
    }

    //登录
    public User login(String username, String password) throws AuthException {
//        System.out.println("进入login");
        try {
            // 1. 查找用户
            User user = userDAO.findByUsername(username);
            System.out.println(user);
            if (user == null) {
                throw new AuthException("用户名或密码错误");
            }

            // 2. 检查账号状态
            if (user.getStatus() == 0) {
                throw new AuthException("账号已被禁用");
            }

            // 3. 验证密码（明文比较）
            if (!password.equals(user.getPassword())) {
                throw new AuthException("用户名或密码错误");
            }

            // 4. 更新最后登录时间
            userDAO.updateLastLoginTime(user.getUserId());

            return user;
        } catch (SQLException e) {
            throw new AuthException("系统错误，请稍后再试", e);
        }
    }

    //查看用户信息
    public User findByUsername(String username) throws SQLException{
        return userDAO.findByUsername(username);
    }

    /**
     * 验证重置码是否有效
     */
    public VerificationCode verifyResetCode(String email, String code,String type) throws SQLException {
        return verificationCodeDAO.getValidCode(email,code,type);
    }

    /**
     * 重置密码
     */
    public boolean resetPassword(String email, String newPassword) throws SQLException {
        // 检查
        return userDAO.resetPassword(email,newPassword);
    }
    public boolean isEmailRegistered(String email) throws SQLException {
        return userDAO.isEmailRegistered(email);
    }

    public boolean updateUser(UserDto user) throws SQLException {
        return userDAO.updateUser(user);
    }
}
